using System.Net.Http;
using AutoMapper;
using Common.Service;
using Dto.ApiRequests.MemberForms;
using NSBus.Dto.Commands;
using NServiceBus;
using Sanelib.Dto;
using Sanelib.Services.Impl;
using WebApp.Services;

namespace WebApp.ControllerApis
{
    public class MemberRegistrationController : SmartApiController
    {
        private readonly IModelService _modelService;
        public IBus Bus { get; set; }
        public MemberRegistrationController(IUserSession userSession, IMappingEngine mappingEngine, IModelService modelService)
            : base(userSession, mappingEngine)
        {
            _modelService = modelService;
        }

        public HttpResponseMessage Post(RegistrationForm form)
        {
            var errorResult = new ErrorResult();
            var isError = _modelService.CheckMemberRegistrationForm(form, errorResult);

            if (!isError)
                return Content(errorResult);

            Bus.Send<RegisterNewMemberCommand>(x =>
            {
                x.Code = form.Code;
                x.Name = form.Name;
                x.DateOfBirth = form.DateOfBirth;
                x.Address = form.Address;
                x.Email = form.Email;
                x.Mobile = form.Mobile;
                x.Url = GetPasswordRecoveryUrl();
            });

            var response = new WebApiResultResponse
            {
                IsSuccess = true,
                Message = "Your registration request has been received. Please check your mail."
            };

            return Content(response);
        }

        private string GetPasswordRecoveryUrl()
        {
            var generalConfig = ConfigProvider.GetGeneralConfig();
            var uri = generalConfig.ApplicationBaseUrl;
            return string.Format("{0}{1}", uri, Url.Route("Default", new { controller = "Auth", action = "Index" }));
        }
    }
}